package com.lori.netshop.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lori.netshop.mapper.TbItemCatMapper;
import com.lori.netshop.mapper.TbItemParamMapper;
import com.lori.netshop.pojo.TbItemCat;
import com.lori.netshop.pojo.TbItemParam;
import com.lori.netshop.pojo.TbItemParamExample;
import com.lori.netshop.pojo.TbItemParamExample.Criteria;
import com.lori.netshop.service.ItemParamService;
import com.lori.netshop.util.NetshopResult;

@Service
public class ItemParamServiceimp implements ItemParamService{
	//注入mapper
	@Autowired
	private TbItemParamMapper tbItemParamMapper;
	@Autowired
	private TbItemCatMapper tbItemCatMapper;
	/**
	 * 功能：根据类别ID获得商品规格
	 * 
	 */
	@Override
	public NetshopResult findByID(long id) {
		TbItemParamExample example = new TbItemParamExample();
		//设置条件
		Criteria criteria = example.createCriteria();
		criteria.andItemCatIdEqualTo(id);
		List<TbItemParam> selectByExample = tbItemParamMapper.selectByExampleWithBLOBs(example);
		if(selectByExample.size() > 0){
			TbItemParam tbItemParam = selectByExample.get(0);
			return NetshopResult.ok(tbItemParam);
		}
		return NetshopResult.ok();
	}
	/**
	 * 功能：保存TbItemParam
	 * 
	 */
	@Override
	public NetshopResult save(TbItemParam itemParam) {
		//补全itemParam
		itemParam.setCreated(new Date());
		itemParam.setUpdated(new Date());
		tbItemParamMapper.insert(itemParam);
		return NetshopResult.ok();
	}
	@Override
	public Map pagination(int page, int rows) {
		//创建map
		Map map = new HashMap();
		TbItemParamExample example = new TbItemParamExample();
		//分页
		PageHelper.startPage(page, rows);
		//获得分页后的数据
		List<TbItemParam> itemparamlist = tbItemParamMapper.selectByExampleWithBLOBs(example);
		//将获得的数据集合遍历，根据cid获得商品分类表的类名字段并加入pojo中
		for(TbItemParam tbItemParam:itemparamlist){
			Long itemCatId = tbItemParam.getItemCatId();
			TbItemCat itemcat = tbItemCatMapper.selectByPrimaryKey(itemCatId);
			tbItemParam.setItemCatName(itemcat.getName());
		}
		//获得总记录数
		PageInfo<TbItemParam> pageinfo = new PageInfo<TbItemParam>(itemparamlist);
		long total = pageinfo.getTotal();
		
		map.put("total", total);
		map.put("rows", itemparamlist);
		
		return map;
	}

}
